import { TYPE_BOOL, TYPE_DOUBLE, TYPE_INT } from '@app-nextmesh/types';
import { isBoolean, isInteger, isNumber } from 'lodash';
import { CheckBox, ErrorTips, NumberInput } from '.';
import { IBaseProps } from './types';

interface IProp extends IBaseProps<number | boolean> {
  type: string;
  disabled: boolean;
}
/**
 * 数值输入框，包含整数、浮点数、布尔值
 * @param {string} type - 类型 int、double、bool
 * @param {number | boolean} value - 值
 * @param {boolean} disabled - 是否禁用
 * @param {function} onValueChange - 值变化回调函数
 * @return {JSX.Element}
 */
export default function ValueInput({
  type,
  value,
  disabled,
  onChange: onInputChange,
}: IProp) {
  let errorMsg = undefined;
  if (type === TYPE_DOUBLE) {
    if (!isNumber(value)) {
      errorMsg = '格式错误，必须是一个数字';
    }
  } else if (type === TYPE_INT) {
    if (!isInteger(value)) {
      errorMsg = '格式错误，必须是一个整数';
    }
  } else if (type === TYPE_BOOL) {
    if (!isBoolean(value)) {
      errorMsg = '格式错误，必须是一个布尔值';
    }
  } else {
    errorMsg = '未知类型';
  }
  if (errorMsg) {
    return <ErrorTips>{errorMsg}</ErrorTips>;
  }
  if (type === TYPE_DOUBLE || type === TYPE_INT) {
    return (
      <NumberInput
        type={type}
        value={value as number}
        disabled={disabled}
        onChange={onInputChange}
      />
    );
  } else if (type === TYPE_BOOL) {
    return (
      <CheckBox
        disabled={disabled}
        checked={value as boolean}
        onChange={(value) => onInputChange(value)}
      />
    );
  } else {
    return <></>;
  }
}
